RDB.php

<?php

require_once(__DIR__.'/SqlVerbs.php');
require_once(__DIR__.'/RdbExtras.php');


// setup Redbean to use our custom beans
define('REDBEAN_MODEL_PREFIX', '\\RDBModel\\');
define('REDBEAN_OODBBEAN_CLASS', '\\RDB\\Bean');

class RDB extends \RedBeanPHP\Facade {

    use RDB\SqlVerbs;
    use RDB\RdbExtras;

    /**
     * force lower-case + underscores only
     */
    static protected function cleanType($type){
        $type = preg_replace('/[^a-z\_]/','',strtolower($type));
        return $type;
    }

    /**
     * execute an sql string
     */
    static public function execute(string $sql, array $binds=[]){
        $binds = static::keysToBinds($binds);
        try {
            static::exec($sql, $binds);
        } catch (\Error $e){
            static::handleException("exec", $e);
        }
    }

    /**
     * execute an sql string & get back the results as an associative array
     */
    static public function query(string $sql, array $binds=[]){
        $binds = static::keysToBinds($binds);
        try {
            return static::getAll($sql, $binds);
        } catch(\Error $e){
            static::handleException('getAll');
        }
    }


    static public function find($type, $sql = NULL, $bindings = [], $snippet = NULL){
        $type = static::cleanType($type);
        try {
            return parent::find($type,$sql,$bindings,$snippet);
        } catch (\Error $e){
            static::handleException('find', $e);
        }
    }

    static public function findOne($type, $sql = NULL, $bindings = [], $snippet = NULL){
        $type = static::cleanType($type);
        try {
            return parent::findOne($type,$sql,$bindings,$snippet);
        } catch (\Error $e){
            static::handleException('findOne', $e);
        }
    }

    public static function dispense($typeOrBeanArray, $num = 1, $alwaysReturnArray = false){
        $type = $typeOrBeanArray;
        if (is_string($typeOrBeanArray)){
            $class = REDBEAN_MODEL_PREFIX.$type;
            // to force autoloading
            $doesExist = class_exists($class,true);
            $type = static::cleanType($type);
        }
        $args = func_get_args();
        array_shift($args);
        try {
            return parent::dispense($type,...$args);
        } catch (\Error $e){
            static::handleException('dispense', $e);
        }
    }
    
    public static function store($bean, $unfreezeIfNeeded = false){
        try {
            return parent::store($bean, $unfreezeIfNeeded);
        } catch (\Error $e) {
            static::handleException('store', $e);
        }
    }
    public static function storeAll($beans, $unfreezeIfNeeded = false){
        try {
            return parent::storeAll($beans, $unfreezeIfNeeded);
        } catch (\Error $e) {
            static::handleException('storeAll', $e);
        }
    }

}